//
//  NewsDetailController.swift
//  MyTouTiao
//
//  Created by Yuri on 2018/3/19.
//  Copyright © 2018年 Yuri. All rights reserved.
//

//新闻详情页

import UIKit
import WebKit
import LeoDanmakuKit
import LLSwitch
import WZLBadge

class NewsDetailController: UIViewController, LLSwitchDelegate {
    
    var webView : WKWebView!
    
    var post : HttpPost!
    
    var isDanMuOpen = true
    
    @IBOutlet weak var danmuView: LeoDanmakuView!
    @IBOutlet weak var danmuSwitch: LLSwitch!
    @IBOutlet weak var commentBtn: UIButton!
    
    //评论按钮被点击
    @IBAction func commentBtnClick(_ sender: UIButton) {
        //点击跳转到评论位置
        doJavaScriptFunction()
    }
    
    //开始编辑
    @IBAction func commentEditBegin(_ sender: UITextField) {
        danmuSwitch.isHidden = true
        commentBtn.isHidden = true
    }
    
    //完成编辑
    @IBAction func commentEditDone(_ sender: UITextField) {
        danmuSwitch.isHidden = false
        commentBtn.isHidden = false
        
        //如果没有值，直接return，否则继续
        guard let commentText = sender.text else { return }
        
        guard commentText != "" else {  return }
        
        print("准备发表评论:\(commentText)")
        
        //发表评论
        NewsListHttpModel.submitComment(postId: post.id, name: "Yuri", email: "123@q2.com", content: commentText) { (success) in
            if success {
                OperationQueue.main.addOperation {
                    self.loadDanMu(comment: commentText)
                    self.showCommentBadge(count: self.post.commentCount + 1)
                    sender.text = ""
                    
                    //通知列表更新
                    NotificationCenter.default.post(name: NotificationHelper.updateList, object: nil)
                }
            } else {
                print("评论失败")
            }
        }
    }
    
    func didTap(_ llSwitch: LLSwitch!) {
        if isDanMuOpen {
            danmuSwitch.setOn(false, animated: true)
            danmuView.stop()
            danmuView.isHidden = true
            print("弹幕关闭")
        } else {
            danmuSwitch.setOn(true, animated: true)
            danmuView.resume()
            danmuView.isHidden = false
            print("弹幕开启")
        }
        isDanMuOpen = !isDanMuOpen
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title = post.title
        
        danmuSwitch.delegate = self

        let frame = CGRect(x: 0, y: 44, width: self.view.frame.width, height: self.view.frame.height - 44 - 20)
        webView = WKWebView(frame: frame)
        //直接追加webview在最上层
//        self.view.addSubview(webView)
        //将webview插入到最底层
        self.view.insertSubview(webView, at: 0)
        
        loadHtml()
        loadDanMu(comments: post.comments)
        showCommentBadge(count: post.commentCount)
    }
    
    func loadHtml() {
        //使用URL加载
        //        let url = URL(string: urlString)
        //        webView.load(URLRequest(url: url!))
        
        //h5移动端优化 viewport 以及图片处理 img
        let header = """
        <!DOCTYPE html>
        <html>
        <head>
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
        <script src="http://localhost:8888/wordpress/wp-content/uploads/2018/03/scroll.js"></script>

        <style>
          img { width: 100% }
        </style>
        </head>
        <body>
        """
        let footer = """
            </body>
            </html>
        """
        
        var commentTopDivider = ""
        if post.commentCount > 0 {
            commentTopDivider = "<hr id=\"commentAnchor\">"
        }
        let comment = commentTopDivider + getCommentHtml(comments: post.comments)
        //使用Content方式加载
        webView.loadHTMLString(header + post.content + comment + footer, baseURL: nil)
    }
    
    //加载弹幕
    //多条弹幕或者加载单条弹幕
    func loadDanMu(comments : [HttpComment]? = nil , comment : String? = nil) {
        if isDanMuOpen {
            danmuView.resume()
            
            if let comments = comments {
                //加载多条弹幕
                let danmus : [LeoDanmakuModel] = comments.map({
                    let danmuModel = LeoDanmakuModel.randomDanmku(withColors: UIColor.danmus, maxFontSize: 30, minFontSize: 15)
                    danmuModel?.text = $0.content.html2String
                    return danmuModel!
                })
                danmuView.addDanmaku(with: danmus)
            }
            
            if let comment = comment {
                //加载单条弹幕
                let danmuModel = LeoDanmakuModel.randomDanmku(withColors: UIColor.danmus, maxFontSize: 30, minFontSize: 15)
                danmuModel?.text = comment
                
                danmuView.addDanmaku(danmuModel)
            }
            
        } else {
            danmuView.stop()
        }
    }
    
    //显示评论角标
    func showCommentBadge(count : Int) {
        commentBtn.badgeCenterOffset = CGPoint(x: -4, y: 5)
        commentBtn.showBadge(with: .number, value: count, animationType: .none)
    }
    
    //拼接评论
    func getCommentHtml(comments : [HttpComment]) -> String {
        var result = ""
        for commment in comments {
            let item = "<p><h6>\(commment.name!)</h6><h5>\(commment.content!)</h5><hr size = 1></hr></p"
            result += item
        }
        return result
    }
    
    func doJavaScriptFunction() {
//        let js = "window.location.hash = \"commentAnchor\""
        let js = """
        ScrollToControl('commentAnchor')
        """
        webView.evaluateJavaScript(js) { (result, error) in
            print("执行完毕：",result,error)
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
